import { ValidationError, validate } from "class-validator";

export function formatBody<T>(
  data: any,
  model: { [key: string]: FeildItem },
): T {
  let newData: T | any = {};
  for (const key in model) {
    if (Object.prototype.hasOwnProperty.call(model, key)) {
      if (
        model[key].required &&
        (data[key] === undefined || data[key] === null)
      ) {
        throw new Error(`${key}不能为空！`);
      }

      if (data[key] !== undefined && data[key] !== null) {
        // 赋值
        newData[key] = data[key];
      }
    }
  }

  return newData;
}

// 校验数据
export async function validatorData<T>(data: T, ClassObj: any) {
  const classObj = new ClassObj();
  for (const key in data) {
    if (Object.prototype.hasOwnProperty.call(data, key)) {
      classObj[key] = data[key];
    }
  }

  const errors: ValidationError[] = await validate(classObj);
  
  errors.forEach((error) => {
    for (const key in error.constraints) {
      if (Object.prototype.hasOwnProperty.call(error.constraints, key)) {
        throw new Error(error.constraints[key]);
      }
    }
  });
}

interface FeildItem {
  type: string;
  required: boolean;
}
